
/*
 * =========================================================================
 *
 *       FileName:  a.c
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  2021-08-09 23:14:10
 *  Last Modified:  2021-08-09 23:15:26
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  zt ()
 *   Organization:
 *
 * =========================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int counter = 0;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
void* doit ( void* )
{
  int i, val;

  for ( i = 0; i < 5000; i++ )
  {
    pthread_mutex_lock ( &g_mutex );
    pthread_mutex_lock ( &g_mutex );
    val = counter;
    printf ( "%x: %d\n", pthread_self(), val + 1 );
    counter = val + 1;
    pthread_mutex_unlock ( &g_mutex );
    pthread_mutex_unlock ( &g_mutex );
  }

  return NULL;
}

int main ( int argc, char* argv[] )
{
  ( void ) argc;
  ( void ) argv;
  pthread_t tid1, tid2;
  pthread_create ( &tid1, NULL, doit, NULL );
  pthread_create ( &tid2, NULL, doit, NULL );
  pthread_join ( tid1, NULL );
  pthread_join ( tid2, NULL );
  return 0;
}
//结果：加1次锁，可以正确的输出1~10000；加2次锁，死锁，不输出任何信息。


